import { MyVue } from '@/common/MyVue';
import { Component } from "vue-facing-decorator";
import Constant, { TopBar } from '@/constant/Constants';
import { UserInfo } from '@/model/UserInfo';
import { UserService } from '@/service/UserService';
import Util from '@/utils/Util';
import StringUtil from '@/utils/StringUtil';
import PostInfo from '@/model/PostInfo';
import { PostService } from "@/service/PostService";
import { PostRequest } from '@/protocol/request/PostRequest';
import LoggerUtil from '@/utils/LoggerUtil';
import UniUtil from '@/utils/UniUtil';
@Component
export default class User extends MyVue {
    cdnHost = Constant.cdnHost;
    recommendList = new Array<UserInfo.SimpleUser>();
    postList = new Array<PostInfo>();
    postMap = new Map<number, PostInfo>();
    showRecommend: boolean = false;
    selectIndex: number = 0;
    selectStatus: number = 0;
    user = new UserInfo.UserData();
    request: PostRequest.QueryList = new PostRequest.QueryList();
    translateX = {
        'transform': '',
        '-webkit-transform': '',
        '-moz-transform': ''
    };
    scrollTop: number = 0; // 用于吸顶处理
    stickyKey: number = 0; // 用于强制刷新 fui-sticky 组件
    isBack: boolean = false; // 用于判断是否是返回操作
    /**
     * 重置吸顶状态，确保组件正确工作
     */
    resetStickyState() {
        // 通过改变 key 值强制重新渲染 fui-sticky 组件
        this.stickyKey++;
        this.$nextTick(() => {
            this.$forceUpdate();
        });
    }

    async onLoad(options: any) {
        uni.setNavigationBarTitle({ title: TopBar.USER });
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }

        // 确保初始化选中状态
        this.selectIndex = 0;
        this.selectStatus = 0;

        // 调用onShow进行数据加载
        await this.onShow();
    }

    async loadPost() {
        let recommendList = await UserService.queryRecommedList(this.request);
        Util.copyList(this.recommendList, recommendList, UserInfo.SimpleUser);
        this.setTabTranslateX();

        // 重置数据和分页状态
        this.postList.length = 0;
        this.request.pageIndex = 1;
        this.request.postId = 0;
        this.request.lnkId = 0;

        await this.loadPostList();

        // 页面加载完成后，计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
            // 确保数据加载后强制更新视图
            this.$forceUpdate();
        });
    }


    async onReachBottom() {
        this.request.pageIndex += 1;
        await this.loadPostList();
    }

    toUser(e) {
        this.isBack = true;
        const uid = e.currentTarget.dataset.id;
        uni.navigateTo({
            url: "/pages/blogger/blogger", success: (res) => {
                res.eventChannel.emit('toUser', { userId: uid });
            }
        });

    }


    async loadPostList() {
        this.request.pageSize = 30;
        if (this.selectIndex == 0) {
            // 作品
            this.request.type = 0;
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.postId = this.postList.length > 0 ? this.postList[this.postList.length - 1].id : 0;
        } else if (this.selectIndex == 1) {
            // 收藏
            this.request.type = 3; // 收藏类型
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.lnkId = this.postList.length > 0 ? this.postList[this.postList.length - 1].lnkId : 0;
        } else if (this.selectIndex == 2) {
            // 喜欢
            this.request.type = 1; // 收藏类型
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.lnkId = this.postList.length > 0 ? this.postList[this.postList.length - 1].lnkId : 0;
        }

        uni.setNavigationBarTitle({ title: this.user.nick });
        this.postMap.clear();
        this.postList.forEach(element => {
            this.postMap.set(element.id, element);
        });

    }

    truncate(str) {
        return Util.truncate(str, 10);
    }
    toLogin() {
        UniUtil.navigateTo("/pages/login/login?from=edit");
    }

    toShare() {
        this.isBack = true;
        UniUtil.navigateTo("/pages/share/share?uid=" + this.user.uid);
    }
    /**
     * 页面显示时重新计算吸顶触发点
     */
    async onShow() {
        await this.getTabOffsetTop();
        LoggerUtil.info("***********************User onShow************************");

        let user = UserService.getUser();
        if (user && user.uid > 0) {
            user = await UserService.getPublicData(user);
            Util.copy(this.user, user);
            uni.setNavigationBarTitle({ title: this.user.nick });

            // 无论是否为返回操作，都需要确保数据已加载
            if (!this.isBack || this.postList.length === 0) {
                await this.loadPost();
            }
        }
        this.isBack = false; // 重置返回状态

        // 确保页面显示时强制刷新视图
        this.$nextTick(() => {
            this.$forceUpdate();
        });
    }

    /**
     * 推荐区显示/隐藏时重新计算吸顶触发点
     */
    onShowRecommend() {
        console.log("onShowRecommend")
        this.showRecommend = !this.showRecommend;

        // 推荐区变化后，重新计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
        });
    }
    setTabTranslateX() {
        Object.keys(this.translateX).forEach(key => {
            let val = this.translateX[key];
            this.translateX[key] = StringUtil.format('translateX({})', [this.selectIndex * 100 + '%']);
        })
    }
    async onTabSelect(e) {
        const targetIndex = parseInt(e.currentTarget.dataset.index);
        const targetId = parseInt(e.currentTarget.dataset.id);

        console.log('点击Tab:', targetIndex, 'ID:', targetId, '当前index:', this.selectIndex);

        if (this.selectIndex == targetIndex) {
            return;
        }

        // 简化状态管理，立即更新Tab状态
        this.selectStatus = targetId;
        this.selectIndex = targetIndex;
        this.setTabTranslateX();

        // 清空数据并重新加载
        this.postList.length = 0;
        this.request.pageIndex = 1;
        this.request.postId = 0; // 重置postId以确保加载新数据
        this.request.lnkId = 0; // 重置lnkId以确保加载新数据

        console.log('开始加载数据...');
        await this.loadPostList();
        console.log('数据加载完成，数据量:', this.postList.length);

        // 确保Tab切换后重新计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
        });

        // 简化吸顶处理，不使用复杂的锁定机制
        const hasContent = this.postList.length > 0;
    }
    generateId(itemId: any, index: any) {
        return itemId + Date.now();
    }


    toPost(e) {
        this.isBack = true;
        const postId = e.currentTarget.dataset.id;
        const lnkId = e.currentTarget.dataset.lnkId  // 如果没有lnkId，默认为0
        let type = this.dataType()
        uni.navigateTo({ url: "/pages/blogger/post?postId=" + postId + "&uid=" + this.request.uid + "&type=" + type + "&lnkId=" + lnkId });
    }

    dataType() {
        if (this.selectIndex == 0) {
            return 0; // 作品
        } else if (this.selectIndex == 1) {
            return 3; // 收藏
        } else if (this.selectIndex == 2) {
            return 1; // 喜欢
        }

    }

    /**
     * 精确的scroll监听，基于用户信息区域高度处理吸顶
     */
    onScroll(e: any) {
        this.scrollTop = e.detail.scrollTop;
        // 启用手动吸顶处理
        this.handleManualSticky(e.detail.scrollTop);
    }

    /**
     * 备选方案：手动吸顶处理，如果 fui-sticky 不稳定可启用
     */
    isTabSticky: boolean = false;
    tabOffsetTop: number = 0;
    tabContainerHeight: number = 80; // Tab容器的实际高度，用于占位

    /**
     * 获取Tab容器的offsetTop值和高度
     */
    async getTabOffsetTop() {
        return new Promise((resolve) => {
            // 延迟一点时间确保DOM完全渲染
            setTimeout(() => {
                // 获取Tab容器的实际高度
                uni.createSelectorQuery().in(this).select('.tab-container-wrapper').boundingClientRect((data: any) => {
                    if (data) {
                        this.tabContainerHeight = data.height || 80; // 获取Tab容器的实际高度
                        console.log('Tab容器高度:', this.tabContainerHeight, '完整信息:', data);
                    }
                }).exec();

                // 获取用户信息区域的高度作为吸顶触发点
                uni.createSelectorQuery().in(this).select('.fui-page__bd-user').boundingClientRect((data: any) => {
                    if (data) {
                        this.tabOffsetTop = data.height + 42.3 || 340; // 如果获取失败，使用默认值
                        console.log('用户信息区域高度:', this.tabOffsetTop);
                        resolve(this.tabOffsetTop);
                    } else {
                        this.tabOffsetTop = 340;
                        resolve(340);
                    }
                }).exec();
            }, 100);
        });
    }

    /**
     * 手动处理吸顶逻辑（备选方案）
     */
    handleManualSticky(scrollTop: number) {
        const shouldSticky = scrollTop >= this.tabOffsetTop;
        if (this.isTabSticky !== shouldSticky) {
            console.log('吸顶状态变化:', shouldSticky, 'Tab容器高度:', this.tabContainerHeight);
            this.isTabSticky = shouldSticky;
        }
    }

    /**
     * 获取图片URL，处理字符串格式的urls
     */
    getImageUrl(urls: string): string {
        LoggerUtil.info("处理图片URL:", urls);
        // 如果是逗号分隔的字符串，取第一个
        LoggerUtil.info("原始urls:", typeof (urls));
        const firstUrl = urls.split(',')[0]?.trim();

        if (!firstUrl) return '';

        // 如果已经是https开头的完整URL，直接使用
        if (firstUrl.startsWith('https')) {
            return firstUrl;
        }

        // 否则拼接CDN域名
        return this.cdnHost + firstUrl;
    }
}